package com.e2oto.seller.common.http;

import android.content.Context;
import android.widget.Toast;

import com.e2oto.seller.common.base.BaseBean;
import com.e2oto.seller.common.utils.LogTools;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * Created by ZhangLiQiang on 2017/8/1.
 */


public class ProgressSubscriber<T> implements ProgressCancelListener, Observer<BaseBean<T>> {

    private ProgressSubscriberOnNextListener<T> mListener;
    private Context mContext;
    private ProgressDialogHandler mHandler;

    public ProgressSubscriber(ProgressSubscriberOnNextListener<T> listener, Context context) {
        this.mListener = listener;
        this.mContext = context;
        mHandler = new ProgressDialogHandler(context, this, true);
    }

    private void showProgressDialog() {
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog() {
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mHandler = null;
        }
    }


    @Override
    public void onError(Throwable e) {
        if (e instanceof SocketTimeoutException) {
            LogTools.e("SocketTimeoutException");
        } else if (e instanceof ConnectException) {
            LogTools.e("ConnectException");
        } else {
            LogTools.e("else network error");
        }
        Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
        dismissProgressDialog();
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    @Override
    public void onSubscribe(Disposable d) {
        showProgressDialog();
    }

    @Override
    public void onNext(BaseBean<T> baseBean) {
        if (mListener != null) {
            if (baseBean.getCode() == 200) {
                mListener.onNext(baseBean.getData());
            } else {
                Toast.makeText(mContext, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
            }

        } else {
            throw new NullPointerException("ProgressSubscriberOnNextListener is null");
        }
    }

    @Override
    public void onCancelProgress() {

    }
}